<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" class="dataForm">
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('申请事项')" prop="actTitle">
            <el-input v-model="form.actTitle" :disabled="fillIn" :placeholder="$t('申请事项')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('版本名称')" prop="name">
            <el-input v-model="form.name" :disabled="fillIn" :placeholder="$t('版本名称')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="$t('预测年度')" prop="predictYear" label-width="120px">
            <date-picker
              v-model="form.predictYear"
              type="year"
              :disabled="fillIn"
              value-format="yyyy"
              :placeholder="$t('预测年度')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="$t('实际年度数')" prop="actualYear" label-width="120px">
            <el-input-number v-model="form.actualYear" :disabled="fillIn" :placeholder="$t('实际年度')" :min="0" :max="20" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="$t('预测年度数')" prop="predictYearNum" label-width="120px">
            <el-input-number v-model="form.predictYearNum" :disabled="fillIn" :placeholder="$t('预测年度数')" :min="0" :max="20" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <el-button v-if="!fillIn" type="info" size="mini" @click="generateHandle(true)">{{ $t('生成') }}</el-button>
            <el-button v-if="form.id" v-hasPermi="['deal:version:import']" type="info" size="mini" @click="exportHandle">{{ $t('导出') }}</el-button>
            <el-button v-if="!areView && form.id" type="info" size="mini" @click="upload.open = true">{{ $t('导入') }}</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-table v-if="!areView" ref="tableTree" :data="form.actualSubjectsList" :cell-style="tableCellClassName" default-expand-all border row-key="id" :tree-props="{children: 'children', hasChildren: 'hasChildren'}" class="">
        <el-table-column :label="$t('指标')" prop="name" class-name="table-tree" width="250" fixed>
          <template v-slot="scope">
            <el-form-item
              v-if="scope.row.parentId !== '0'"
            >
              <el-input v-model="scope.row.name" :placeholder="$t('指标')" :maxlength="100" :disabled="scope.row.areModify === 'N'" />
            </el-form-item>
            <span v-else>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('指标属性')" align="center" prop="properties" min-width="100" fixed>
          <template v-slot="scope">
            <el-form-item
              v-if="scope.row.parentId !== '0'"
            >
              <el-select v-model="scope.row.properties" :placeholder="$t('指标属性')" :disabled="scope.row.areModify === 'N'">
                <el-option
                  v-for="(item) in indicatorPropertiesOptions"
                  :key="item.dictValue"
                  :value="item.dictValue"
                  :label="item.dictLabel"
                />
              </el-select>
            </el-form-item>
            <span v-else>{{ scope.row.properties }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('单位')" align="center" prop="unit" min-width="100" fixed>
          <template v-slot="scope">
            <el-form-item
              v-if="scope.row.parentId !== '0'"
            >
              <el-input v-model="scope.row.unit" :placeholder="$t('单位')" :maxlength="5" :disabled="scope.row.areModify === 'N'" />
            </el-form-item>
            <span v-else>{{ scope.row.unit }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-for="(item) in yearColumnArray"
          :key="item.prop"
          :prop="item.prop"
          :label="$t(item.label)"
          align="center"
          width="130"
        >
          <template v-slot="scope">
            <el-form-item
              v-if="item.prop.indexOf('C') === -1 && scope.row.parentId !== '0'"
            >
              <money v-model="scope.row[item.prop]" :placeholder="$t('指标值')" @change="calculationCompleteHandle(item['calculation'],scope)" />
            </el-form-item>
            <span v-else>{{ scope.row[item.prop] }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="!fillIn" :label="$t('操作')" align="center" width="80" fixed="right">
          <template v-slot="scope">
            <el-button v-if="scope.row.parentId === '0' && scope.row.areSubItem === 'Y'" type="text" size="mini" @click="addHandle(scope.row)">{{ $t("添加子项") }}</el-button>
            <el-button v-if="scope.row.parentId !== '0'" type="text" icon="el-icon-delete" @click="delHandle(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <div v-else>
        <el-table :data="form.actualSubjectsList" :cell-style="tableCellClassName" border row-key="id" default-expand-all :tree-props="{children: 'children', hasChildren: 'hasChildren'}" class="">
          <el-table-column :label="$t('指标')" prop="name" width="250" fixed />
          <el-table-column :label="$t('排序')" align="center" prop="sort" fixed />
          <el-table-column :label="$t('指标属性')" align="center" prop="properties" fixed :formatter="indicatorPropertiesFormat" />
          <el-table-column :label="$t('单位')" align="center" prop="unit" fixed />
          <el-table-column
            v-for="(item) in yearColumnArray"
            :key="item.prop"
            :prop="item.prop"
            :label="item.label"
            align="center"
            width="130"
          />
        </el-table>
      </div>
    </el-form>
    <div v-if="!otherBtnHide && !showBtn" slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <FormBtn ref="formBtn" :btn-hide="btnHide" :bus-data="form" has-permi="deal:version" :menu-key="menuKey" />
    </div>

    <div v-if="fillIn && !areView" slot="footer" class="dialog-footer" style="text-align: right;">
      <save-btn has-permi="deal:version" />
    </div>

    <!-- 导入窗口 -->
    <el-dialog :title="$t('导入')" :visible.sync="upload.open" width="400px" :close-on-click-modal="false" :lock-scroll="false" append-to-body>
      <div>
        <el-upload
          ref="upload"
          v-loading="upload.isUploading"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="getHeaders"
          :action="upload.url"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :on-exceed="handleFileExceed"
          :on-change="handleFileChange"
          :auto-upload="false"
          drag
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">
            {{ $t('将文件拖到此处，或') }}
            <em>{{ $t('点击上传') }}</em>
          </div>
          <div slot="tip" class="el-upload__tip" style="color:red">
            {{ $t('提示：仅允许导入“xls”或“xlsx”格式文件！') }}
          </div>
        </el-upload>

        <div slot="footer" class="dialog-footer" style="text-align: right;">
          <el-button @click="upload.open = false">{{ $t("取消") }}</el-button>
          <el-button type="primary" @click="submitFileForm">{{ $t("确定") }}</el-button>
        </div>
      </div>
    </el-dialog>

  </div>
</template>

<script>
    import { saveDealIndicatorPredictVersion, getDealIndicatorPredictVersion, getIndicatorByDealId } from '@/api/deal/predict/version/dealIndicatorPredictVersion'
    import { getDealName } from '@/api/base/deal/dealBase'
    import { v4 as uuidv4 } from 'uuid'
    import { getToken } from '@/utils/auth'
    export default {
      props: {
        fillIn: {
          type: Boolean,
          default: false,
          desc: '是否填写指标'
        },
        areView: {
          type: Boolean,
          default: false,
          desc: '是否查看'
        }
      },
        data() {
            return {
              // 菜单标识
                btnHide: false,
                menuKey: 'deal_indicator_predict_version',
                // 表单参数
                form: {
                  actualSubjectsList: []
                },
                // 表单校验
                rules: {
                    name: [
                        { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                    ],
                    predictYear: [
                        { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                    ],
                    actualYear: [
                        { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                    ],
                    predictYearNum: [
                        { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                    ],
                    actTitle: [
                      { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                    ]
                },
                // 遮罩层
                loading: false,
                // 操作按钮默认不展示
                buttonShow: true,
                yearColumnArray: [],
                dealId: this.$route.query.id,
                companyId: this.$route.query.companyId,
              // 指标属性字典
              indicatorPropertiesOptions: [],
              otherBtnHide: false,
              showBtn: false,
              columnProperty: {},
              upload: {
                // 是否显示弹出层（项目导入）
                open: false,
                // 弹出层标题（项目导入）
                title: '',
                // 是否禁用上传
                isUploading: false,
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + '/version/dealIndicatorPredictVersion/importIndicator'
              }
            }
        },
      computed: {
        getHeaders: function() {
          return { Authorization: 'Bearer ' + getToken(), versionId: this.form.id }
        }
      },
        created() {
          this.getDicts('indicator_properties').then(response => {
            this.indicatorPropertiesOptions = response.data
          })
        },
      mounted() {
        this.$bus.$emit('async_done')
        this.showBtn = this.$parent.$options.name === 'ProcessPhase'
      },
      methods: {
            // 初始化数据
            init(data) {
                this.loading = true
                if (data != null && data.id !== undefined) {
                  getDealIndicatorPredictVersion(data.id).then(response => {
                    this.form = response.data
                    this.generateHandle(false)
                    this.receiveAnalyzeProperties()
                    this.loading = false
                  })
                } else {
                    this.reset()
                    this.loading = false
                }
            },
            // 表单重置
            reset() {
                this.form = {
                    id: undefined,
                    dealId: this.dealId,
                    companyId: this.companyId,

                    name: undefined,

                    predictYear: undefined,

                    actualYear: undefined,

                    predictYearNum: undefined,

                    actTitle: undefined,

                    actId: undefined,

                    actStatus: undefined,

                    createBy: undefined,

                    createTime: undefined,

                    updateBy: undefined,

                    updateTime: undefined,

                    delFlag: undefined,
                    subjectsList: [], // 实际存库列表
                    actualSubjectsList: [] // 实际展示列表

                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                if (this.$parent.$parent.formOpen !== undefined) {
                    this.$parent.$parent.formOpen = false
                }
                // 刷新list页面
                if (this.$parent.$parent.getList !== undefined) {
                  this.$parent.$parent.getList()
                }
            },
            /** 提交按钮 */
            submitForm: function(type) {
                return new Promise((resolve, reject) => {
                  this.$refs['form'].validate(valid => {
                    // 验证数据
                    if (valid) {
                      // 弹出遮罩层
                      this.loading = true
                      this.returnAnalyzeProperties()
                      // 保存数据
                      saveDealIndicatorPredictVersion(this.form).then(response => {
                        if (response.code === 200) {
                          // 点击的按钮是保存并启动流程
                          if (type === 'process') {
                            // 启动流程
                            this.startProcess(response.data.id)
                            // 点击的仅保存
                          } else {
                            this.msgSuccess(this.$t('保存成功'))
                            this.form.id = response.data.id
                            resolve(response.data.id)
                            // 关闭form页面
                            this.closeForm()
                          }
                        } else {
                          this.msgError(response.msg)
                          this.loading = false
                          reject(response)
                        }
                      }).catch(() => {
                        this.loading = false
                      })
                    } else {
                      reject()
                      this.locationError(document)
                    }
                  })
                })
           },
            // 启动流程
           startProcess: async function(dataId) {
              var dealName = await getDealName(this.$route.query.id)
               this.loading = false
               // 启动流程时候传入的参数
               const processData = {}
               // 待办标题
               processData.title = '「' + dealName + '」' + ':' + this.form.actTitle
               // 业务表名
               processData.dataTable = 'deal_indicator_predict_version'
               // 业务ID
               processData.dataId = dataId
               // 业务表单地址(待办页面需要打开的页面)
               processData.formPath = '@/views/deal/predict/version/dealIndicatorPredictVersionForm.vue'
               // 菜单标识(根据菜单标识判断的走哪个流程)
               processData.menuKey = this.menuKey
               this.startProcessByMenu(processData, () => {
                   this.form.actStatus = 'D'
                   this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
                   this.closeForm()
               })
           },
          generateHandle(flag) {
            this.loading = true
            this.yearColumnArray = []
            for (let i = this.form.actualYear; i > 0; i--) {
              const yearColumn = {}
              yearColumn['prop'] = Number(this.form.predictYear) - i + 'A'
              yearColumn['label'] = Number(this.form.predictYear) - i + 'A'
              yearColumn['calculation'] = false
              this.yearColumnArray.push(yearColumn)
            }
            for (let i = 0; i < this.form.predictYearNum; i++) {
              const yearColumn = {}
              yearColumn['prop'] = Number(this.form.predictYear) + i + 'E'
              yearColumn['label'] = Number(this.form.predictYear) + i + 'E'
              // 是否参与计算完成情况
              yearColumn['calculation'] = true
              this.yearColumnArray.push(yearColumn)
              if (this.form.actStatus === 'W') {
                const actualYearColumn = {}
                actualYearColumn['prop'] = Number(this.form.predictYear) + i + 'A'
                actualYearColumn['label'] = Number(this.form.predictYear) + i + 'A'
                // 是否参与计算完成情况
                actualYearColumn['calculation'] = true
                this.yearColumnArray.push(actualYearColumn)
                const completeColumn = {}
                completeColumn['prop'] = Number(this.form.predictYear) + i + 'C'
                completeColumn['label'] = this.$t('完成情况(%)')
                this.yearColumnArray.push(completeColumn)
              }
            }
            if (flag) {
              getIndicatorByDealId(this.dealId).then(res => {
                this.form.actualSubjectsList = res.data
                this.loading = false
              })
            } else {
              this.loading = false
            }
          },
          // 返回后端时解析属性 例：2021A: 128.01 解析为: year:2021 type: a value: 128.01
          returnAnalyzeProperties() {
            this.form.subjectsList = []
            this.form.actualSubjectsList.forEach((item1) => {
              const data = {
                id: item1.id,
                parentId: item1.parentId,
                name: item1.name,
                sort: item1.sort,
                properties: item1.properties,
                versionId: item1.versionId,
                unit: item1.unit,
                areSubItem: item1.areSubItem,
                areModify: item1.areModify,
                children: []
              }
              item1.children.forEach((item2) => {
                const children = {
                  id: item2.id,
                  parentId: item2.parentId,
                  name: item2.name,
                  sort: item2.sort,
                  properties: item2.properties,
                  versionId: item2.versionId,
                  unit: item2.unit,
                  areSubItem: item2.areSubItem,
                  areModify: item2.areModify,
                  detailList: []
                }
                this.yearColumnArray.forEach((item3) => {
                  const detail = {
                    year: item3.prop.substring(0, 4),
                    type: item3.prop.substring(4),
                    value: item2[item3.prop],
                    versionId: item2.versionId,
                    subjectsId: item2.id
                  }
                  children.detailList.push(detail)
                })
                data.children.push(children)
              })
              this.form.subjectsList.push(data)
            })
          },
          // 接收后端时解析属性
          receiveAnalyzeProperties() {
            this.form.actualSubjectsList = []
            this.form.subjectsList.forEach((item1) => {
              const data = {
                id: item1.id,
                parentId: item1.parentId,
                name: item1.name,
                sort: item1.sort,
                properties: item1.properties,
                versionId: item1.versionId,
                unit: item1.unit,
                areSubItem: item1.areSubItem,
                areModify: item1.areModify,
                children: []
              }
              item1.children.forEach((item2) => {
                const children = {
                  id: item2.id,
                  parentId: item2.parentId,
                  name: item2.name,
                  sort: item2.sort,
                  properties: item2.properties,
                  unit: item2.unit,
                  areSubItem: item2.areSubItem,
                  areModify: item2.areModify,
                  versionId: item2.versionId
                }
                this.yearColumnArray.forEach((item3) => {
                  item2.detailList.forEach((item4) => {
                    if (item3.prop === (item4.year + item4.type)) {
                      children[item3.prop] = item4.value
                    }
                  })
                })
                data.children.push(children)
              })
              this.form.actualSubjectsList.push(data)
            })
          },
          addHandle(row) {
              const data = {
                id: uuidv4,
                parentId: row.id,
                name: undefined,
                sort: row.children.length > 0 ? row.children[row.children.length - 1].sort + 1 : 1,
                properties: undefined,
                versionId: undefined
              }
              row.children.push(data)
          },
          delHandle(row) {
            for (let i = 0; i < this.form.actualSubjectsList.length; i++) {
              if (this.form.actualSubjectsList[i].id === row.parentId) {
                const element = this.form.actualSubjectsList[i]
                for (let j = 0; j < element.children.length; j++) {
                  if (element.children[j].id === row.id) {
                    this.form.actualSubjectsList[i].children.splice(j, 1)
                    return false
                  }
                }
              }
            }
          },
        indicatorPropertiesFormat(row) {
          return this.selectDictLabel(this.indicatorPropertiesOptions, row.properties)
        },
        tableCellClassName({ row, column, columnIndex }) {
          if (columnIndex !== 0 && this.columnProperty['property'].indexOf('A') !== -1 && column.property.indexOf('C') !== -1) {
            return this.getColorStyle(row[column.property])
          }
          this.columnProperty['property'] = column.property
          return ''
        },
        exportHandle() {
          this.downLoadExcel('/version/dealIndicatorPredictVersion/exportIndicator/' + this.form.id, undefined)
        },
        // 文件上传中处理
        handleFileUploadProgress() {
          this.upload.isUploading = true
        },
        // 文件上传成功处理
        handleFileSuccess(response) {
          this.upload.open = false
          this.upload.isUploading = false
          this.$refs.upload.clearFiles()
          if (response.msg === 'success') {
            this.msgSuccess(this.$t('导入成功'))
          } else if (response.code === 500) {
            this.msgError(response.msg)
          } else {
            this.$alert(response.msg, this.$t('导入结果'), { dangerouslyUseHTMLString: true })
          }
          // this.$alert(response.msg, '导入结果', { dangerouslyUseHTMLString: true })
          this.init({ id: this.form.id })
        },
        // 提交上传文件
        submitFileForm() {
          this.$refs.upload.submit()
        },
        // 文件达到上限处理
        handleFileExceed() {
          this.msgError(this.$t('可上传文件数量已达到上限'))
        },
        // 文件上传变更时间
        handleFileChange(file, fileList) {
          if (!(file.name.indexOf('xls') >= 0 && file.name.indexOf('xlsx') >= 0)) {
            this.msgError(this.$t('仅允许导入“xls”或“xlsx”格式文件！'))
            fileList.splice(0, 1)
          }
        },
        calculationCompleteHandle(calculation, { row, column }) {
          if (calculation) {
            const year = column.property.substring(0, 4)
            const type = column.property.substring(4)
            let e, a
            if (type === 'E') {
              e = row[year + type]
              a = row[year + 'A']
            } else {
              a = row[year + type]
              e = row[year + 'E']
            }
            debugger
            if (row.properties === 'Z') {
              if (e && a && !isNaN(e) && !isNaN(a)) {
                row[year + 'C'] = (a / e * 100).toFixed(2)
              }
            } else {
              if (e && a && !isNaN(e) && !isNaN(a)) {
                row[year + 'C'] = ((1 - (a - e) / e) * 100).toFixed(2)
              }
            }
          }
        },
        getColorStyle(value) {
          if (value >= 100) {
            return 'color:#73d13d'
          } else if (value >= 70) {
            return 'color:#ffc53d'
          } else if (value >= 50) {
            return 'color:#EA7154'
          } else {
            return 'color:#272D30'
          }
        }
      }
    }
</script>

<style scoped>
.table-tree .el-form-item__content {
  margin-left: 0 !important;
}
.table-tree .el-form-item {
  display: inline-block;
}
</style>
